package com.yxh.lib_base.ext.view.textview

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.text.style.ImageSpan

/**
 * 作者 : yuan_xh
 * 时间 : 2022/11/9 13:24
 * 说明 : 废弃，请使用[VerticalImageSpan]
 */
@Deprecated("算法不大准，待优化")
class CenterImageSpan : ImageSpan {
    private var isCenter = true
    private var lineHeight = 0

    constructor(context: Context, bitmap: Bitmap) : super(context, bitmap)
    constructor(drawable: Drawable) : super(drawable)

    //居中
    fun asCenter(center: Boolean = true): CenterImageSpan {
        this.isCenter = center
        return this
    }

    fun setLineHeight(height: Int): CenterImageSpan {
        lineHeight = height
        return this
    }

    /***/
    @Deprecated("算法不大准，待优化")
    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        if (isCenter) {
            if (lineHeight <= 0) {
                val b = drawable
                val fm = paint.fontMetricsInt
                val transY = (y + fm.descent + y + fm.ascent) / 2 - (top + bottom) / 2//计算y方向的位移
                canvas.save()
                canvas.translate(x, transY.toFloat()) //绘制图片位移一段距离
                b.draw(canvas)
                canvas.restore()
            } else {
                val b = drawable
                val fm = paint.fontMetricsInt
                //计算y方向的位移
//                val oY = (y + fm.ascent + y + fm.descent)
//                var offsetY: Int = (y + fm.ascent + y + fm.descent) / 2 - (top + bottom) / 2
                val tY = ((bottom + top) - lineHeight) / 2
//                Log.e(
//                    "==>",
//                    "oY=${oY}  " + "offsetY=${offsetY}  " + "tY=${tY} " + "lineHeight=${lineHeight} " + "top=${top} " + "bottom=${bottom} " + "y=${y} fm:${fm} \nbounds:${b.bounds}"
//                )
                canvas.save()
                canvas.translate(x, tY.toFloat()) //绘制图片位移一段距离
                b.draw(canvas)
                canvas.restore()
            }
        } else {
            super.draw(canvas, text, start, end, x, top, y, bottom, paint)
        }
    }
}